const NET = require("net");

// create once server
const Server = NET.createServer((clientSocket) => {
    console.log(clientSocket);

    clientSocket.on('error', (err) => {
        console.log(err);
    });

    console.log(clientSocket.address(), 'address')
    
     // 接收方法二 按照utf8码表翻译回来
     // hex 把接收buf转为二进制字符串
     // 默认接收的是buf对象
    clientSocket.setEncoding("utf8");
    clientSocket.on('data', (msg) => {
        console.log(msg);
        //接收方法1
        //console.log(new Buffer(msg).toString("utf8"));
        setInterval(() => {
            // 这里也可不用new Buffer 因为默认把字符串按照utf8编码专二进制
            clientSocket.write(new Buffer("sql"));
            //clientSocket.end(1); // 相当于关闭和对方的连接
        },1000)
    });

    clientSocket.on('close', () => {
        console.log('closed')
    })
});

// start listen
Server.listen({
    host: '0.0.0.0',
    port: '1334',
    exclusive: true
}, () => {
    console.log('listen server in 0.0.0.0 port is 1334');
});


// event
Server.on('close', () => {
    console.log('the server is closed');
});

Server.on('error', (err) => {
    console.log(err);
});

Server.on('connection', (sk) => {
    console.log('client connection');
    console.log(sk);
});

// close server
setTimeout(() => {
    console.log('unref');
    Server.unref();
}, 4000);

// ref server
setTimeout(() => {
    console.log('ref');
    Server.ref();
}, 18000)



Server.close();